package nowCoder;

/**
 * Created by Ghost on 2015/3/24.
 * Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
 For example,
 Given1->2->3->3->4->4->5, return1->2->5.
 Given1->1->1->2->3, return2->3.

 */
public class Remove_duplicates_from_sorted_list_ii {
    private boolean judgeDuplicate(ListNode cur){
        if(cur!=null && cur.next!=null){
            if(cur.val == cur.next.val)
                return true;
        }
        return false;
    }
    public ListNode deleteDuplicates(ListNode head) {
        if(head==null)
            return null;

        ListNode pre = null, cur = head;
        while(cur!=null){
            if(judgeDuplicate(cur)){
                if(pre==null){
                    while(cur!=null && cur.val==head.val){
                        cur = cur.next;
                    }
                    head = cur;
                    pre = null;
                } else{
                    int v = cur.val;
                    while(cur!=null && cur.val==v){
                        cur = cur.next;
                    }
                    pre.next = cur;
                }
            } else{
                pre = cur;
                cur = cur.next;
            }
        }
        return head;
    }

    public static void main(String[] args){
        Remove_duplicates_from_sorted_list_ii remove_duplicates_from_sorted_list_ii = new Remove_duplicates_from_sorted_list_ii();
        ListNode root = new ListNode(1);
      /*  root.next = new ListNode(3);
        root.next.next = new ListNode(3);
        root.next.next.next = new ListNode(3);
        root.next.next.next.next = new ListNode(4);*/
        ListNode rst = remove_duplicates_from_sorted_list_ii.deleteDuplicates(null);
        while(rst!=null){
            System.out.println(rst.val);
            rst = rst.next;
        }

    }
}
